#!/usr/local/bin/perl -w
# Parsing log of GB, NC, CI ...
use strict;
use Template;
use CGI;
require JCL;


my $tt_file = 'result.html';

#my $mmdd=$ENV{'QUERY_STRING'};

#my $mmdd = '0728';

my $query = CGI->new;
my @names = $query->param;
#print "$_\n" foreach @names;
my $mmdd = $query->param("$names[0]");
#print "mmdd=$mmdd\n";
my $file = $query->param("$names[1]");
#print "file=$file\n";
my $dir = "/home/ftpuser/";
my $logdir = "/home/ftpuser/";
my $log = $logdir . 'log/' . $mmdd . '.log';
my $files;

if (! -e $log) {  # the log file not found since not upload
  $|=1;
  print "Content-type: text/html\n\n";
  print "log file of $mmdd not found!\n\n";
}
elsif ($file eq 'all') {
  my $URL = "http://10.16.7.140/$mmdd.html";

  print "Status: 302 Moved\nLocation: $URL\n\n";  ## redirect
}
else {
  $|=1;
  print "Content-type: text/html\n\n";

}

#--- build {file => jobs} hash
#--- key is 'file' => value is 'jobs array ref.'
  my $today;
  my $hhmm = &JCL::date_time('hhmm');
  if ($hhmm <= 830) {
    $today = &JCL::date_time('yesterday');
  }
  else {
    $today = &JCL::date_time('today');
  }
$dir = $dir . "$mmdd/" if $today ne $mmdd;

my $jobs = &JCL::get_job_list($dir, $file);

#--- test data structure -----
#while (my ($key, $value) = each %file_jobs ) {
#  print "$key => \n";
#  print "$_\n" foreach @$value;
#}

#--- read log file every line into array
my @logs;
my $i = 0;
# $mmdd = &JCL::date_time('yesterday') unless $mmdd;

open (LOG, "< $log")
|| die "Cannot open $log: $!";

while (<LOG>) {
#  @logs = <LOG>;
  $logs[$i] = $_;
  $i++;
}
close LOG;


#-- get the analyzed period of logs
my $period;
if ($logs[1] =~ m/(\d{7}) (\d{2}:\d{2}:\d{2}\.\d{2})/) {
   $period = &JCL::date_from_yday($1) . " " . substr($2, 0, 5);
}
if ($logs[$#logs -1] =~ m/(\d{7}) (\d{2}:\d{2}:\d{2}\.\d{2})/) {
   $period = $period . ' ~ ' . &JCL::date_from_yday($1) . " " . substr($2, 0, 5);
}  


#-- build jobno => userid hash from scanning log
my $jobno_userid_ref = &JCL::scan_log_for_jobno_and_userid(\@logs);


#-- build releasd & releasing hash from scanning file
my ($released_ref, $releasing_ref) = &JCL::get_released_releasing($dir, $file);

#-- parsing log for matching job name to get Date Time JobNo JobName StepName RC
#--- build {job => found_log} hash
#--- key is 'job' => value is 'steps of this job array ref.' (Date Time JobNo JobName StepName RC)


my $vars = {
#    joblist    => &JCL::file_jobs_get_result(\%file_jobs, \@logs, $jobno_userid_ref, $released_ref, $releasing_ref),
     joblist    => &JCL::file_jobs_get_result($file, $jobs, \@logs, $jobno_userid_ref, $released_ref, $releasing_ref),
##         must passing array ref. to template toolkit not array
    period     => $period,
    file       => $file,
};


my $template = Template->new({
    INCLUDE_PATH => '/usr/lib/cgi-bin/src:/usr/lib/cgi-bin/lib',
    PRE_PROCESS  => 'config',
});

$template->process($tt_file, $vars)
    || die $template->error();

